package com.iot08.admin.controller;

import com.alibaba.fastjson.JSONObject;
import com.aliyun.tea.utils.StringUtils;
import com.iot08.admin.controller.base.BaseController;
import com.iot08.admin.service.*;
import com.iot08.admin.service.page.PageVO;
import com.iot08.admin.service.page.PageableImpl;
import com.iot08.admin.utils.RedisEnum;
import com.iot08.admin.vo.ImportDeviceReqVO;
import com.iot08.common.config.redis.RedisService;
import com.iot08.common.constant.Const;
import com.iot08.common.entity.admin.Channel;
import com.iot08.common.entity.admin.SysUser;
import com.iot08.common.entity.app.*;
import com.iot08.common.entity.util.ChangeAddress;
import com.iot08.common.response.Response;
import com.iot08.common.utils.RegexUtil;
import com.iot08.common.utils.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.List;
import java.util.UUID;

/**
 * @version 1.0
 * @Description: 设备相关
 * @author: Rock
 * @time: 2020/8/27 9:06
 */
@Slf4j
@Controller
@RequestMapping("device")
public class DeviceController extends BaseController {

    @Resource
    private ChannelService channelService;
    @Resource
    private DeviceService deviceService;

    @Resource
    private NotifyService notifyService;
    @Resource
    private DeviceModelsService deviceModelsService;
    @Resource
    private VideoModelService videoModelService;
    @Resource
    private DeviceImsiService deviceImsiService;
    @Resource
    private EntryRecordService entryRecordService;
    @Resource
    private ShiftService shiftService;
    @Resource
    private RedisService redisService;
    @Resource
    private ChannelAreaService channelAreaService;

    // 接入联通DMP 平台的 账号信息表操作对象
    @Resource
    private DmpAccountService dmpAccountService;

    @Value("${device.import.path: }")
    private String importPath;


    /**
     * 设备列表
     *
     * @param page, channelCode
     * @time: 2020/8/27 9:07
     * @author: Rock
     * @version 1.0
     */
    @RequestMapping("list")
    public ModelAndView list(PageVO page,
                             @RequestParam(value = "channelCode", required = false) Long channelCode,
                             @RequestParam(value = "name", required = false) String name,
                             @RequestParam(value = "phone", required = false) String phone,
                             @RequestParam(value = "deviceModelId", required = false) String deviceModelId) {
        ModelAndView mv = new ModelAndView();
        Page<Device> pages = deviceService.list(page, channelCode,deviceModelId, this.getSessionUser());
        mv.addObject("devices", pages.getContent());
        if (pages.getPageable() instanceof PageableImpl) {
            PageableImpl pi = (PageableImpl) pages.getPageable();
            mv.addObject("page", pi.getPage());
        }
        mv.addObject("channelCode", channelCode);
        mv.addObject("name", name);
        mv.addObject("phone", phone);
        mv.addObject("butSet", getMyBut(page.getMenuId()));
        mv.addObject("channels", channelService.listAll(this.getSessionUser()));
        mv.addObject("deviceModelId",deviceModelId);
        mv.addObject("deviceModels",getDevModels());
        mv.setViewName("device/device_list");
        return mv;
    }

    /**
     * @description 导出数据
     * @author cwj
     * @param [imei, channelCode, name, phone, deviceModelId]
     * @return void
     * @date @time 2025/4/20 10:16
     **/
    @RequestMapping("import")
    public void importData(@RequestParam(value = "imei", required = false) String imei,
                            @RequestParam(value = "channelCode", required = false) Long channelCode,
                            @RequestParam(value = "name", required = false) String name,
                            @RequestParam(value = "phone", required = false) String phone,
                            @RequestParam(value = "deviceModelId", required = false) String deviceModelId,HttpServletResponse response) {
        deviceService.importData(imei, channelCode,deviceModelId, this.getSessionUser(),response);
    }

    /**
     * operateDev 操作设备
     * @param imei
     * @param operate 0:定位 1:远程关机
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = "operateDev", method = RequestMethod.POST)
    public Response<Object> operateDev(@RequestParam("id") String imei,
                                       @RequestParam("operate") Integer operate) throws Exception {
        SysUser sysUser = getSessionUser();
        if(sysUser.getType() == Const.CHANNELUSER_TYPE){
            return Response.failedResponse("无权限操作");
        }
        return notifyService.deviceControl(imei, operate, sysUser);
    }

    /**
     * @Description: 添加页面
     * @time: 2020/8/17 17:21
     * @author: Rock
     * @version 1.0
     */
    @RequestMapping("toAdd")
    public ModelAndView toAdd() {
        ModelAndView mv = new ModelAndView();
        mv.addObject("channels", channelService.listAll(this.getSessionUser()));
        mv.setViewName("device/device_add");
        return mv;
    }

    /**
     * 设备录入页面
     *
     * @time: 2020/8/27 18:22
     * @author: Rock
     * @version 1.0
     */
    @RequestMapping("toImportDevice")
    public ModelAndView toImportDevice() {
        ModelAndView mv = new ModelAndView();
        mv.addObject("channels", getChannels());
        mv.addObject("devModels", getDevModels());
//        mv.addObject("watchStoreChannels", deviceService.getWatchStoreChannel());
        //接入联通DMP平台的 多账号
//        mv.addObject("dmpAccountIds", dmpAccountService.getAllAccount());
        mv.setViewName("device/device_import");
        return mv;
    }

    /**
     * 设备录入
     *
     * @param vo
     * @param request
     * @time: 2020/10/28 17:50
     * @author: Rock
     * @version 1.0
     */
    @ResponseBody
    @RequestMapping(value = "importDevice", method = RequestMethod.POST)
    public Response<Object> importDevice(ImportDeviceReqVO vo, MultipartHttpServletRequest request) throws Exception {
        boolean isJFvideolimit553 = false;
        //渠道商ID，设备型号ID
        DeviceModels deviceModel = deviceModelsService.findById(vo.getDevModelId());
        if (deviceModel.getVideo_modelid() != null) {
            //如果选择了视频类型的都是有 553 限制(现在随视频类型的规则变化了)的
            isJFvideolimit553 = true;
        }
        if (vo.getType() == 0) {
            //单个录入
            return deviceService.add(vo, this.getSessionUser(), this.getRemortIP(), isJFvideolimit553);
        } else {
            //批量录入
            MultipartFile file = request.getFile("file");
            if (file == null || file.isEmpty()) {
                return Response.failedResponse("请上传文件");
            }
            String fileSuffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1);
            if (!"xls".equals(fileSuffix.toLowerCase()) && !"xlsx".equals(fileSuffix.toLowerCase())) {
                return Response.failedResponse("请上传excel文件");
            }
            return deviceService.importDevice(vo, this.getSessionUser(), this.getRemortIP(), file, isJFvideolimit553);
        }
    }

    /**
     * 查找页面
     *
     * @time: 2020/8/31 9:23
     * @author: Rock
     * @version 1.0
     */
    @RequestMapping("toSearch")
    public ModelAndView toSearch() {
        ModelAndView mv = new ModelAndView();
        mv.setViewName("device/device_search");
        return mv;
    }

    /**
     * 查找设备
     *
     * @param type
     * @param imei
     * @param request
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = "search", method = RequestMethod.POST)
    public Response<Object> search(Integer type, @RequestParam(required = false) String imei,
                                   MultipartHttpServletRequest request) throws Exception {
        SysUser user = this.getSessionUser();
        if (type == 0) {
            if (StringUtil.isBlank(imei)) {
                return Response.failedResponse("请输入需要查找的设备IMEI/MEID号");
            } else {
                Device device = deviceService.findById(imei);
                if (device != null) {
                    if (user.getType() == Const.CHANNELUSER_TYPE) {
                        if (user.getChannelArea() != null) {
                            List<String> areaIdList = channelAreaService.listIdById(user.getChannelAreaId(), true);
                            if (device.getChannelAreaId() != null && areaIdList.contains(device.getChannelAreaId())) {
                                return Response.successResponse("设备号存在");
                            } else {
                                return Response.successResponse("设备号存在，但无权限访问该设备");
                            }
                        } else {
                            if (StringUtil.isBlank(device.getAgent()) ||
                                    user.getChannelAff().getChannelCodes().contains(device.getAgent())
                                    || DeviceService.excludeAgent.contains(device.getAgent())) {
                                return Response.successResponse("设备号存在");
                            } else {
                                return Response.successResponse("设备号存在，但无权限访问该设备");
                            }
                        }
                    } else {
                        return Response.successResponse("设备号存在");
                    }
                } else {
                    return Response.successResponse("设备号不存在");
                }
            }
        } else {
            MultipartFile file = request.getFile("file");
            if (file == null) {
                return Response.failedResponse("请上传查找的excel文件");
            } else {
                String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1);
                if (!"xls".equals(suffix) && !"xlsx".equals(suffix)) {
                    return Response.failedResponse("请上传excel文件");
                }
                return deviceService.searchByExcel(user, file);
            }
        }
    }

    /**
     * 查找页面
     *
     * @time: 2020/8/31 9:23
     * @author: Rock
     * @version 1.0
     */
    @RequestMapping("toSearchImsi")
    public ModelAndView toSearchImsi() {
        ModelAndView mv = new ModelAndView();
        mv.setViewName("device/device_imsi_search");
        return mv;
    }

    /**
     * @param imei
     * @time: 2020/10/20 15:58
     * @author: Rock
     * @version 1.0
     */
    @ResponseBody
    @RequestMapping(value = "searchImsi", method = RequestMethod.POST)
    public Response<Object> searchImsi(String imei) {
        return deviceImsiService.searchImsi(imei, this.getSessionUser());
    }

    /**
     * @param imei
     * @time: 2020/10/20 18:00
     * @author: Rock
     * @version 1.0
     */
    @ResponseBody
    @RequestMapping(value = "exportImsi", method = RequestMethod.POST)
    public Response<Object> exportImsi() throws Exception {
        return deviceImsiService.exportImsi(this.getSessionUser());
    }

    /**
     * 查找设备激活情况页面
     *
     * @time: 2020/8/31 9:23
     * @author: Rock
     * @version 1.0
     */
    @RequestMapping("toSearchActive")
    public ModelAndView toSearchActive() {
        ModelAndView mv = new ModelAndView();
        mv.setViewName("device/device_active_search");
        return mv;
    }

    /**
     * @param imei
     * @time: 2020/10/20 15:58
     * @author: Rock
     * @version 1.0
     */
    @ResponseBody
    @RequestMapping(value = "searchActive", method = RequestMethod.POST)
    public Response<Object> searchActive(Integer type, @RequestParam(required = false) String imei,
                                         MultipartHttpServletRequest request) throws Exception {
        SysUser user = this.getSessionUser();
        if (type == 0) {
            if (StringUtil.isBlank(imei)) {
                return Response.failedResponse("请输入需要查找的设备IMEI/MEID号");
            } else {
                return deviceService.searchAcviteByImei(user, imei);
            }
        } else {
            MultipartFile file = request.getFile("file");
            if (file == null) {
                return Response.failedResponse("请上传查找的excel文件");
            } else {
                String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1);
                if (!"xls".equals(suffix) && !"xlsx".equals(suffix)) {
                    return Response.failedResponse("请上传excel文件");
                }
                return deviceService.searchActiveByExcel(user, file);
            }
        }
    }

    /**
     * 下载Excel
     *
     * @param [path, response]
     * @time: 2020/8/31 15:58
     * @author: Rock
     * @version 1.0
     */
    @ResponseBody
    @RequestMapping(value = "/downloadExcel", method = RequestMethod.GET)
    public void downloadExcel(Integer type, @RequestParam(required = false) String fileName, HttpServletResponse response) throws IOException {
        SysUser user = this.getSessionUser();
        String path = "";
        if (type == -1) {
            path = importPath + File.separator + fileName;
        } else if (type == 0) {
            path = importPath + File.separator + user.getId() + "-found.xlsx";
        } else if (type == 1) {
            path = importPath + File.separator + user.getId() + "-not_found.xlsx";
        } else if (type == 2) {
            path = importPath + File.separator + user.getId() + "-not_.xlsx";
        } else if (type == 3) {
            path = importPath + File.separator + user.getId() + "-not_del.xlsx";
        } else if (type == 4) {
            path = importPath + File.separator + user.getId() + "-found_not_jurisdiction.xlsx";
        } else if (type == 5) {
            path = importPath + File.separator + "repetition_imsi.xlsx";
        } else {
            return;
        }
        InputStream in = null;
        try {
            in = new FileInputStream(new File(path));
        } catch (FileNotFoundException e) {
            log.info("not exist file : " + path);
            e.printStackTrace();
            return;
        }
        byte[] getData = this.readInputStream(in);
        String[] fileNameList = path.split("/");
        // 设置文件ContentType类型，这样设置，会自动判断下载文件类型
        String name = new String(fileNameList[fileNameList.length - 1].getBytes("GBK"), "ISO-8859-1");
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setHeader("Content-Disposition", "attachment;filename=" + name);
        try {
            // 用流将数据写给前端
            OutputStream os = response.getOutputStream();
            os.write(getData);
            os.flush();
            os.close();
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }
        in.close();
    }

    /**
     * 解绑页面
     *
     * @time: 2020/8/31 9:23
     * @author: Rock
     * @version 1.0
     */
    @RequestMapping("toUnbind")
    public ModelAndView toUnbind() {
        ModelAndView mv = new ModelAndView();
        mv.addObject("user", this.getSessionUser());
        mv.setViewName("device/device_unbind");
        return mv;
    }

    /**
     * 设备挂失解绑页面
     * @param
     * @time: 1/10/22 11:01 PM
     * @author: Weichao
     * @version 1.0
     */
    @RequestMapping("toLossDevUnbind")
    public ModelAndView toLossDevUnbind() {
        ModelAndView mv = new ModelAndView();
        mv.addObject("user", this.getSessionUser());
        mv.setViewName("device/device_loss_unbind");
        return mv;
    }

    /**
     * 解绑设备
     *
     * @param type
     * @param imei
     * @param request
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = "unbind", method = RequestMethod.POST)
    public Response<Object> unbind(Integer type, @RequestParam(required = false) String imei,
                                   MultipartHttpServletRequest request) throws Exception {
        SysUser user = this.getSessionUser();
        if (type == 0) {
            if (StringUtil.isBlank(imei)) {
                return Response.failedResponse("请输入需要解绑的设备IMEI/MEID号");
            } else if (!RegexUtil.validateDeviceId(imei)) {
                return Response.failedResponse("解绑失败,请检查imei格式是否正确");
            } else {
                return deviceService.unbindByImei(user, imei, this.getRemortIP(), false);
            }
        } else {
            MultipartFile file = request.getFile("file");
            if (file == null) {
                return Response.failedResponse("请上传解绑的excel文件");
            } else {
                String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1);
                if (!"xls".equals(suffix) && !"xlsx".equals(suffix)) {
                    return Response.failedResponse("请上传excel文件");
                }
                return deviceService.unbindByExcel(user, file, this.getRemortIP());
            }
        }
    }

    /**
     * 挂失设备 解绑设备
     *
     * @param type
     * @param imei
     * @param request
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = "lossDevUnbind", method = RequestMethod.POST)
    public Response<Object> lossDevUnbind(Integer type, @RequestParam(required = false) String imei,
                                          MultipartHttpServletRequest request) throws Exception {
        SysUser user = this.getSessionUser();
        if (type == 0) {
            if (StringUtil.isBlank(imei)) {
                return Response.failedResponse("请输入需要解绑的设备IMEI/MEID号");
            } else if (!RegexUtil.validateDeviceId(imei)) {
                return Response.failedResponse("解绑失败,请检查imei格式是否正确");
            } else {
                return deviceService.unbindByImei(user, imei, this.getRemortIP(), true);
            }
        }
        return Response.failedResponse("解绑失败, 不支持多个解绑");
    }


    /**
     * 根据解绑设备任务ID查询进度
     *
     * @param workId
     * @param request
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = "getunbind", method = RequestMethod.POST)
    public Response<Object> getUnbindWithWorkId(@RequestParam(required = false) String workId,
                                                MultipartHttpServletRequest request) throws Exception {
//        SysUser user = this.getSessionUser();
        if (workId == null){
            return Response.failedResponse("无 workId");
        }
        String workInfoJsonStr = redisService.get(workId);
        JSONObject workInfo = JSONObject.parseObject(workInfoJsonStr);
        /*
        {
            "count": XX,
            "index": XX,
            "success": XX,
            "showMsg": XX,
            "down_url": XX
        }
        */
        log.info("根据解绑设备workId:{} 查询进度:{}", workId, workInfoJsonStr);
        return Response.successResponse(workInfo);
    }


    /**
     * 删除页面
     *
     * @time: 2020/9/1 9:01
     * @author: Rock
     * @version 1.0
     */
    @RequestMapping("toDel")
    public ModelAndView toDel() {
        ModelAndView mv = new ModelAndView();
        mv.setViewName("device/device_del");
        return mv;
    }

    /**
     * 删除
     *
     * @param type
     * @param imei
     * @param request
     * @time: 2020/10/28 15:45
     * @author: Rock
     * @version 1.0
     */
    @ResponseBody
    @RequestMapping(value = "del", method = RequestMethod.POST)
    public Response<Object> del(Integer type, @RequestParam(required = false) String imei,
                                MultipartHttpServletRequest request) throws Exception {
        SysUser user = this.getSessionUser();
        if (type == 0) {
            if (StringUtil.isBlank(imei)) {
                return Response.failedResponse("请输入需要删除的设备IMEI/MEID号");
            } else if (!RegexUtil.validateDeviceId(imei)) {
                return Response.failedResponse("删除失败,请检查imei格式是否正确");
            } else {
                return deviceService.delByImei(user, imei, this.getRemortIP());
            }
        } else {
            MultipartFile file = request.getFile("file");
            if (file == null) {
                return Response.failedResponse("请上传删除的excel文件");
            } else {
                String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1);
                if (!"xls".equals(suffix) && !"xlsx".equals(suffix)) {
                    return Response.failedResponse("请上传excel文件");
                }
                return deviceService.delByExcel(user, file, getRemortIP());
            }
        }
    }
    /*================= 设备型号 ===================*/
    @RequestMapping("listDevModel")
    public ModelAndView listDevModel(PageVO page, String s_agentId, String s_devModelId) {
        ModelAndView mv = new ModelAndView();

        //全面的厂商类型
        mv.addObject("agents", getChannels());
        //全部的设备类型
        mv.addObject("devModels", getDevModels());
        if(!StringUtils.isEmpty(s_agentId)){
            mv.addObject("s_agentId", s_agentId);
        }
        if(!StringUtils.isEmpty(s_devModelId)){
            mv.addObject("s_devModelId", s_devModelId);
        }

        Page<DeviceModels> pages = deviceModelsService.list(page, s_agentId, s_devModelId, this.getSessionUser());
        if (pages.getPageable() instanceof PageableImpl) {
            PageableImpl pi = (PageableImpl) pages.getPageable();
            mv.addObject("page", pi.getPage());
        }
        pages.forEach(dm -> {
            if(dm.getVenderName() == null){
                for (Channel ch: getChannels()) {
                    if(dm.getVender().equals(""+ch.getChannelCode())){
                        dm.setVenderName(ch.getName());
                    }
                }
            }
        });

        mv.addObject("devModelList", pages.getContent());
        mv.addObject("butSet", getMyBut(page.getMenuId()));
        mv.setViewName("device/device_models");
        return mv;
    }

    /**
     * @Description: 跳到 添加设备型号 的页面
     */
    @RequestMapping("toAddModel")
    public ModelAndView toAddModel() {
        ModelAndView mv = new ModelAndView();
        mv.addObject("channels", getChannels());
        List<VideoModel> videoModels = videoModelService.listAll();
        mv.addObject("videoModels", videoModels);
        mv.setViewName("device/device_models_add");
        return mv;
    }
    /**
     * @Description: 跳到 编辑设备型号 的页面
     */
    @RequestMapping("toEditModel")
    public ModelAndView toEditModel(String id, Integer showType) {
        ModelAndView mv = new ModelAndView();
        List<Channel> channels = getChannels();
        DeviceModels models = deviceModelsService.findById(id);
        if(StringUtil.isBlank(models.getVenderName())){
            for (Channel item: channels) {
                if(models.getVender().equals(""+item.getChannelCode()) ){
                    models.setVenderName(item.getName());
                }
            }
        }
        mv.addObject("models", models);
        mv.addObject("channels", channels);
        List<VideoModel> videoModels = videoModelService.listAll();
        mv.addObject("videoModels", videoModels);
        mv.addObject("showType", showType);
        mv.setViewName("device/device_models_edit");
//        if (Const.INT_1.equals(showType)) {
//            mv.setViewName("device/device_models_show");
//        } else {
//            mv.setViewName("device/device_models_edit");
//        }
        return mv;
    }


    /**
     * 保存 设备型号 的接口
     */
    @RequestMapping(value = "addModel", method = RequestMethod.POST)
    public ModelAndView addModel(DeviceModels devModel) {
        ModelAndView mv = new ModelAndView();
        SysUser user = this.getSessionUser();
        Boolean res = deviceModelsService.check(null, devModel.getModel());
        if (res) {
            //用UUID字符串代替
            devModel.setId(UUID.randomUUID().toString());
            deviceModelsService.save(devModel, user, this.getRemortIP());
            //保存完成后清除一下缓存的 设备型号列表
            deviceModelsList.clear();
            mv.addObject("msg", "success");
        } else {
            mv.addObject("msg", "设备型号名称已存在!");
        }
        mv.setViewName("save_result");
        return mv;
    }

    /**
     * 编辑 设备型号 的接口
     */
    @RequestMapping(value = "editModel", method = RequestMethod.POST)
    public ModelAndView editModel(DeviceModels devModel) {
        ModelAndView mv = new ModelAndView();
        SysUser user = this.getSessionUser();
        Integer res = deviceModelsService.updateDevModel(devModel, user, this.getRemortIP());
        if (res == 0) {
            //更新完成后清除一下缓存的 设备型号列表
            deviceModelsList.clear();
            mv.addObject("msg", "success");
        } else if (res == 1) {
            //已有导入设备,不允许修改
            mv.addObject("msg", "已有导入设备,不允许修改");
        } else {
            mv.addObject("msg", "设备型号更新失败,未知原因,请联系管理员");
        }
        mv.setViewName("save_result");
        return mv;
    }

    /**
     * 删除 设备型号 的接口
     */
    /*@ResponseBody
    @RequestMapping(value = "delModle", method = RequestMethod.POST)
    public ModelAndView delModle(@RequestParam("id") String devModelId) {
        ModelAndView mv = new ModelAndView();
        SysUser user = this.getSessionUser();
        if(user.getType() == Const.CHANNELUSER_TYPE){
            //渠道账号无法删除设备型号
            mv.addObject("msg", "无权操作");
            mv.setViewName("save_result");
            return mv;
        }

        DeviceModels models = deviceModelsService.findById(devModelId);
        if(models == null){
            mv.addObject("msg", "该型号不存在");
            mv.setViewName("save_result");
            return mv;
        }
        if(models.getActive_num() > 0){
            mv.addObject("msg", "该型号已激活,不能删除,如需删除,请联系技术人员");
            mv.setViewName("save_result");
            return mv;
        }
        Boolean res = deviceModelsService.del(devModelId, user, this.getRemortIP(), models.getModel());
        if (res) {
            //更新完成后清除一下缓存的 设备型号列表
            deviceModelsList.clear();
            mv.addObject("msg", "success");
        } else {
            mv.addObject("msg", "设备型号更新失败,未知原因,请联系管理员");
        }
        mv.setViewName("save_result");
        return mv;
    }*/

    @ResponseBody
    @RequestMapping(value = "delModle", method = RequestMethod.POST)
    public Response<Object> delModle(@RequestParam("id") String devModelId) {
        SysUser user = this.getSessionUser();
        if(user.getType() == Const.CHANNELUSER_TYPE){
            //渠道账号无法删除设备型号
            return Response.failedResponse("无权操作");
        }
        DeviceModels models = deviceModelsService.findById(devModelId);
        if(models == null){
            return Response.failedResponse("该型号不存在");
        }
        if(models.getActive_num() > 0){
            return Response.failedResponse("该型号已激活,不能删除,如需删除,请联系技术人员");
        }
        //模型下存在设备，也不能删除
        if(deviceService.checkDeviceExistsByModleId(devModelId)){
            return Response.failedResponse("该型号已经有设备在使用,不能删除,如需删除,请联系技术人员");
        }
        Boolean res = deviceModelsService.del(devModelId, user, this.getRemortIP(), models.getModel());
        if (res) {
            //更新完成后清除一下缓存的 设备型号列表
            deviceModelsList.clear();
            return Response.successResponse("success");
        } else {
            return Response.failedResponse("设备型号更新失败,未知原因,请联系管理员");
        }
    }


    /******************************* 设备激活情况 *************************/

    /**
     * @param page, agentUsername, telecom, startTime, endTime
     * @time: 2020/9/9 10:21
     * @author: Rock
     * @version 1.0
     */
    @RequestMapping("listEntryRecord")
    public ModelAndView listEntryRecord(PageVO page, String agentUsername, Integer telecom,
                                        String startTime, String endTime,Integer isQueryStatistic) {
        ModelAndView mv = new ModelAndView();
        Page<EntryRecord> pages = entryRecordService.list(page, agentUsername, telecom, startTime, endTime, this.getSessionUser());
        mv.addObject("enteryRecords", pages.getContent());
        if (pages.getPageable() instanceof PageableImpl) {
            PageableImpl pi = (PageableImpl) pages.getPageable();
            mv.addObject("page", pi.getPage());
        }
        //mv.addObject("channels", getChannels());
        mv.addObject("channels", channelService.listAll(this.getSessionUser()));
        mv.addObject("agentUsername", agentUsername);
        mv.addObject("telecom", telecom);
        mv.addObject("startTime", startTime);
        mv.addObject("endTime", endTime);
        mv.addObject("butSet", getMyBut(page.getMenuId()));
        mv.addObject("deviceTotalTime", redisService.get(RedisEnum.DeviceTotalTime.getKey()));
        mv.addObject("isQueryStatistic",isQueryStatistic);
        if(ObjectUtils.isNotEmpty(isQueryStatistic) && Integer.valueOf(1).equals(isQueryStatistic)){
            mv.addObject("entryRecordStatisticsResp",entryRecordService.queryStatisticsData(page.getSearchValue(),agentUsername, telecom, startTime, endTime, this.getSessionUser()));
        }
        mv.setViewName("device/entery_record_list");
        return mv;
    }

    /**************************** 设备家庭成员 *********************************/

    @RequestMapping("listDeviceMember")
    public ModelAndView listDeviceMember(PageVO page, String phone){
        ModelAndView mv = new ModelAndView();
        Page<Device> pages = deviceService.list(page, phone, null, this.getSessionUser());
        mv.addObject("devices", pages.getContent());
        if(pages.getPageable() instanceof PageableImpl){
            PageableImpl pi = (PageableImpl)pages.getPageable();
            mv.addObject("page", pi.getPage());
        }
        mv.addObject("phone", phone);
//        mv.addObject("usrPhone", usrPhone);
        mv.addObject("butSet", getMyBut(page.getMenuId()));
        //家庭成员头像
        //mv.addObject("sysfileDomain", sysfileDomain);

        mv.setViewName("device/device_member_list");
        return mv;
    }

    /**************************** 远程监控 *********************************//*

    @RequestMapping("listRemoteControl")
    public ModelAndView listRemoteControl(PageVO page){
        ModelAndView mv = new ModelAndView();
        Page<Device> pages = deviceService.list(page, null, null, null, this.getSessionUser());
        mv.addObject("devices", pages.getContent());
        if(pages.getPageable() instanceof PageableImpl){
            PageableImpl pi = (PageableImpl)pages.getPageable();
            mv.addObject("page", pi.getPage());
        }
        mv.addObject("butSet", getMyBut(page.getMenuId()));
        mv.addObject("sysfileDomain", sysfileDomain);
        mv.setViewName("device/device_remote_control");
        return mv;
    }

    *//**
     * 发送定位
     * @param [id]
     * @time: 2020/9/11 14:29
     * @author: Rock
     * @version 1.0
     *//*
    @ResponseBody
    @RequestMapping(value = "sendLocation", method = RequestMethod.POST)
    public Response<Object> sendLocation(String id) {
        return deviceService.sendLocation(id, this.getSessionUser(), this.getRemortIP());
    }

    *//**
     * 远程关机
     * @param [id]
     * @time: 2020/9/11 14:56
     * @author: Rock
     * @version 1.0
     *//*
    @ResponseBody
    @RequestMapping(value = "remoteShutdown", method = RequestMethod.POST)
    public Response<Object> remoteShutdown(String id) {
        return deviceService.remoteShutdown(id, this.getSessionUser(), this.getRemortIP());
    }*/


    /********************** 视频通话相关 ******************************/

    /**
     * @time: 2020/10/29 15:21
     * @author: Rock
     * @version 1.0
     */
    @RequestMapping("toSearchCallDuration")
    public ModelAndView toSearchCallDuration() {
        ModelAndView mv = new ModelAndView();
        mv.setViewName("videoModel/call_duration_search");
        return mv;
    }

    /**
     * 设备通话分钟数数查询
     *
     * @param imei
     * @time: 2020/10/29 14:45
     * @author: Rock
     * @version 1.0
     */
    @ResponseBody
    @RequestMapping("searchCallDuration")
    public Response<Object> searchCallDuration(String imei) {
        return deviceService.searchCallDuration(imei, this.getSessionUser());
    }

    /**
     * @time: 2020/10/29 15:43
     * @author: Rock
     * @version 1.0
     */
    @RequestMapping("toResetFree")
    public ModelAndView toResetFree() {
        ModelAndView mv = new ModelAndView();
        mv.setViewName("videoModel/reset_free");
        return mv;
    }

    /**
     * @param imei
     * @time: 2020/10/29 15:43
     * @author: Rock
     * @version 1.0
     */
    @ResponseBody
    @RequestMapping("resetFree")
    public Response<Object> resetFree(String imei) {
        return deviceService.resetFree(imei, this.getSessionUser(), this.getRemortIP());
    }

    /**
     * @time: 2020/10/29 16:17
     * @author: Rock
     * @version 1.0
     */
    @RequestMapping("toForceOneReset")
    public ModelAndView toForceOneReset() {
        ModelAndView mv = new ModelAndView();
        mv.setViewName("videoModel/force_one_reset");
        return mv;
    }

    /**
     * @param imei
     * @time: 2020/10/29 15:43
     * @author: Rock
     * @version 1.0
     */
    @ResponseBody
    @RequestMapping("forceOneReset")
    public Response<Object> forceOneReset(String imei) {
        return deviceService.forceOneReset(imei, this.getSessionUser(), this.getRemortIP());
    }

    /**
     * @time: 2020/10/29 16:17
     * @author: Rock
     * @version 1.0
     */
    @RequestMapping("toOneReset")
    public ModelAndView toOneReset() {
        ModelAndView mv = new ModelAndView();
        mv.setViewName("videoModel/one_reset");
        return mv;
    }

    /**
     * @param imei
     * @time: 2020/10/29 15:43
     * @author: Rock
     * @version 1.0
     */
    @ResponseBody
    @RequestMapping("oneReset")
    public Response<Object> oneReset(String imei) {
        return deviceService.oneReset(imei, this.getSessionUser(), this.getRemortIP());
    }

    /**
     * @time: 2020/10/29 16:17
     * @author: Rock
     * @version 1.0
     */
    @RequestMapping("toOneShift")
    public ModelAndView toOneShift() {
        ModelAndView mv = new ModelAndView();
        mv.setViewName("videoModel/one_shift");
        return mv;
    }

    /**
     * @param imei
     * @time: 2020/10/29 15:43
     * @author: Rock
     * @version 1.0
     */
    @ResponseBody
    @RequestMapping("oneShift")
    public Response<Object> oneShift(String oldImei, String newImei) {
        return deviceService.oneShift(oldImei, newImei, this.getSessionUser());
    }

    /**
     * @param page
     * @param newImei
     * @time: 2020/10/29 17:41
     * @author: Rock
     * @version 1.0
     */
    @RequestMapping("listShift")
    public ModelAndView listShift(PageVO page, String newImei) {
        ModelAndView mv = new ModelAndView();
        Page<Shift> pages = shiftService.list(page, newImei);
        mv.addObject("shifts", pages.getContent());
        if (pages.getPageable() instanceof PageableImpl) {
            PageableImpl pi = (PageableImpl) pages.getPageable();
            mv.addObject("page", pi.getPage());
        }
        mv.addObject("newImei", newImei);
        mv.addObject("butSet", getMyBut(page.getMenuId()));
        mv.setViewName("videoModel/device_shift_list");
        return mv;
    }

    /**
     * @description 切换设备推送数据的地址
     * @author cwj
     * @param []
     * @return org.springframework.web.servlet.ModelAndView
     * @date @time 2025/2/27 15:17
     **/
    @RequestMapping("toChange")
    public ModelAndView toChange() {
        ModelAndView mv = new ModelAndView();
        mv.setViewName("device/device_change_address");
        return mv;
    }

    /**
     * @description 切换设备推送数据的地址
     * @author cwj
     * @param [changeAddress]
     * @return com.iot08.common.response.Response<java.lang.Object>
     * @date @time 2025/2/27 16:23
     */
    @ResponseBody
    @PostMapping("changeAddress")
    public Response<Object> changeAddress(ChangeAddress changeAddress) throws IOException {
        if(StringUtils.isEmpty(changeAddress.getImei()) ||
                StringUtils.isEmpty(changeAddress.getIp()) || ObjectUtils.isEmpty(changeAddress.getPort())){
            return Response.failedResponse("参数错误，存在未传值的参数");
        }
        //检查有没有权限操作
        SysUser sysUser = getSessionUser();
        if(sysUser.getType() == Const.CHANNELUSER_TYPE){
            return Response.failedResponse("无权限操作");
        }
        //return deviceService.changeAddress(changeAddress);
        return notifyService.changeAddress(changeAddress,sysUser);
    }
}
